package com.huawei.mytestapp.slice;
import net.sourceforge.zbar.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.DirectionalLayout.LayoutConfig;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.utils.LayoutAlignment;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.camera.CameraKit;
import ohos.media.camera.device.*;
import ohos.media.common.BufferInfo;

import ohos.media.image.ImageReceiver;
import ohos.media.image.common.ImageFormat;
import static ohos.media.camera.device.Camera.FrameConfigType.FRAME_CONFIG_PREVIEW;

//java类导入
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;


public class MainAbilitySlice extends AbilitySlice {
    private HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP,0,"chencongxiao");
    private ImageScanner scanner;
    private DirectionalLayout myLayout;
    private ImageReceiver imageReceiver;
    private CameraKit cameraKit;
    private SurfaceProvider surfaceProvider;
    private Surface previewSurface;
    private Surface dataSurface;
    private Camera mcamera;
    private Text scanText;
    private boolean barcodeScanned = false;
    private boolean previewing = true;
    private List<String> list;
    private EventRunner runner;
    private EventHandler handler;


    public static final int VIDEO_WIDTH = 640;
    public static final int VIDEO_HEIGHT = 480;


    private Button button;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        runner = EventRunner.getMainEventRunner();
        handler = new EventHandler(runner);

        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        //初始化UI和相机，实现视频帧的获取
        initUIandCamera();
        //注册编码器，实现视频帧的编码
        registerEncoder();
        //注册发送，实现编码数据的发送

    }

    private void initUIandCamera(){
        //布局容器
        myLayout = new DirectionalLayout(this);
        LayoutConfig config = new LayoutConfig(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_PARENT);
        myLayout.setLayoutConfig(config);
        myLayout.setOrientation(Component.VERTICAL);
        myLayout.setPadding(32,32,32,32);
        //SurfaceProvider，用于播放摄像头画面
        config.width = VIDEO_WIDTH;
        config.height = VIDEO_HEIGHT;
        config.alignment = LayoutAlignment.HORIZONTAL_CENTER;
        surfaceProvider = new SurfaceProvider(this);
        surfaceProvider.setLayoutConfig(config);
        surfaceProvider.getSurfaceOps().get().addCallback(callback);
        surfaceProvider.pinToZTop(true);
        //Button，点击开始编码和发送
        config.height = LayoutConfig.MATCH_CONTENT;
        config.width = LayoutConfig.MATCH_CONTENT;
        config.setMargins(0,50,0,0);
        scanText = new Text(this);
        scanText.setTextSize(100);
        scanText.setMultipleLine(true);
        scanText.setText("扫描中" );
        scanText.setLayoutConfig(config);
//        button = new Button(this);
//        button.setLayoutConfig(config);
//        button.setText("Scanning...");
//        button.setTextSize(50);
//        ShapeElement background = new ShapeElement();
//        background.setRgbColor(new RgbColor(0xFF51A8DD));
//        background.setCornerRadius(25);
//        button.setBackground(background);
//        button.setClickedListener(new Component.ClickedListener() {
//            @Override
//            public void onClick(Component component) {
//                if (barcodeScanned) {
//                    barcodeScanned = false;
//
//                    previewing = true;
//
//                }
//
//            }
//        });
        //添加组件添加到布局容器中，并将布局容器作为UI的根布局

        myLayout.addComponent(surfaceProvider);
//        myLayout.addComponent(button);
        myLayout.addComponent(scanText);
        super.setUIContent(myLayout);
    }




    private void registerEncoder() {


        //创建ImageReceiver并配置监听器
        imageReceiver = ImageReceiver.create(VIDEO_WIDTH, VIDEO_HEIGHT, ImageFormat.YUV420_888, 10);
        IImageArrivalListenerImpl listener = new IImageArrivalListenerImpl();
        imageReceiver.setImageArrivalListener(listener);
    }
    //监听器，当有数据进入ImageReceiver时触发
    private class IImageArrivalListenerImpl implements ImageReceiver.IImageArrivalListener {
        //对监听事件的响应逻辑，实现对图像数据处理和到编码器的传输
        @Override
        public void onImageArrival(ImageReceiver imageReceiver) {

            ohos.media.image.Image mImage = imageReceiver.readNextImage();
            if (mImage != null) {
                BufferInfo bufferInfo = new BufferInfo();
                ByteBuffer mBuffer;
//                byte[] DATA = new byte[VIDEO_HEIGHT*VIDEO_WIDTH];
//                mBuffer = mImage.getComponent(ImageFormat.ComponentType.JPEG).getBuffer();





                byte[] YUV_DATA = new byte[VIDEO_HEIGHT * VIDEO_WIDTH * 3 / 2];
                int i;
                //采集YUV格式数据
                mBuffer = mImage.getComponent(ImageFormat.ComponentType.YUV_Y).getBuffer();
                for (i = 0; i < VIDEO_WIDTH * VIDEO_HEIGHT; i++) {
                    YUV_DATA[i] = mBuffer.get(i);
                }
                mBuffer = mImage.getComponent(ImageFormat.ComponentType.YUV_V).getBuffer();
                for (i = 0; i < VIDEO_WIDTH * VIDEO_HEIGHT / 4; i++) {
                    YUV_DATA[(VIDEO_WIDTH * VIDEO_HEIGHT) + i * 2] =
                            mBuffer.get(i * 2);
                }
                mBuffer = mImage.getComponent(ImageFormat.ComponentType.YUV_U).getBuffer();
                for (i = 0; i < VIDEO_WIDTH * VIDEO_HEIGHT / 4; i++) {
                    YUV_DATA[(VIDEO_WIDTH * VIDEO_HEIGHT) + i * 2 + 1] = mBuffer.get(i * 2);
                }

                bufferInfo.setInfo(0, VIDEO_WIDTH * VIDEO_HEIGHT * 3 / 2, mImage.getTimestamp(), 0);
                Image barcode =  new Image(mImage.getImageSize().width, mImage.getImageSize().height, "Y800");
                barcode.setData(YUV_DATA);

                int result = scanner.scanImage(barcode);

                if (result != 0) {

                    HiLog.fatal(hiLogLabel,"succeed");
//                    mcamera.stopLoopingCapture();
//                    mcamera.release();
                    SymbolSet syms = scanner.getResults();
//                    scanText.setText("34wefsdf");
                    HiLog.fatal(hiLogLabel, String.valueOf(syms.size()));
                    list = new ArrayList<>(syms.size());

                    for (Symbol sym : syms) {
                        handler.postTask(new Runnable() {
                            @Override
                            public void run() {
                                scanText.setText("扫描结果:" + sym.getData());
                                scanText.invalidate();

                            }
                        });
//                        scanText.setText("barcode result " + sym.getData());
                        HiLog.fatal(hiLogLabel,"扫描结果: " + sym.getData());

                        barcodeScanned = true;

                    }
//                    scanText.invalidate();
                }



                mImage.release();
                return;
            }
        }
    }

    private void openCamera(){
        // 获取 CameraKit 对象
        cameraKit = CameraKit.getInstance(this);
        if (cameraKit == null) {
            return;
        }
        try {
            // 获取当前设备的逻辑相机列表cameraIds
            String[] cameraIds = cameraKit.getCameraIds();
            if (cameraIds.length <= 0) {
                System.out.println("cameraIds size is 0");
            }
            // 用于相机创建和相机运行的回调
            CameraStateCallbackImpl cameraStateCallback = new CameraStateCallbackImpl();
            if(cameraStateCallback ==null) {
                System.out.println("cameraStateCallback is null");
            }
            // 创建用于运行相机的线程
            EventHandler eventHandler = new EventHandler(EventRunner.create("CameraCb"));
            if(eventHandler ==null) {
                System.out.println("eventHandler is null");
            }
            // 创建相机！
            cameraKit.createCamera(cameraIds[0], cameraStateCallback, eventHandler);
        } catch (IllegalStateException e) {
            System.out.println("getCameraIds fail");
        }
    }


    private final class CameraStateCallbackImpl extends CameraStateCallback {
        //相机回调
        @Override
        public void onCreated(Camera camera) {
            mcamera = camera;
            //相机创建时回调
            CameraConfig.Builder cameraConfigBuilder = camera.getCameraConfigBuilder();
            if (cameraConfigBuilder == null) {
                System.out.println("onCreated cameraConfigBuilder is null");
                return;
            }
            // 配置预览的 Surface
            cameraConfigBuilder.addSurface(previewSurface);
            // 配置拍照的 Surface
            dataSurface = imageReceiver.getRecevingSurface();
            cameraConfigBuilder.addSurface(dataSurface);
            try {
                // 相机设备配置
                camera.configure(cameraConfigBuilder.build());
            } catch (IllegalArgumentException e) {
                System.out.println("Argument Exception");
            } catch (IllegalStateException e) {
                System.out.println("State Exception");
            }
        }
        @Override
        public void onConfigured(Camera camera) {
            FrameConfig.Builder frameConfigBuilder = mcamera.getFrameConfigBuilder(FRAME_CONFIG_PREVIEW);
            // 配置预览 Surface
            frameConfigBuilder.addSurface(previewSurface);
            // 配置拍照的 Surface
            frameConfigBuilder.addSurface(dataSurface);
//                    frameConfigBuilder.setAfMode(1);
            try {
                // 启动循环帧捕获
                int triggerId = mcamera.triggerLoopingCapture(frameConfigBuilder.build());
            } catch (IllegalArgumentException e) {
                System.out.println("Argument Exception");
            } catch (IllegalStateException e) {
                System.out.println("State Exception");
            }
            //相机配置

        }
        @Override
        public void onReleased(Camera camera) {
            // 释放相机设备
            if (mcamera != null) {
//                previewing = false;
                mcamera.stopLoopingCapture();
                mcamera.release();
                mcamera = null;
            }
        }
    }

    private SurfaceOps.Callback callback = new SurfaceOps.Callback() {
        @Override
        public void surfaceCreated(SurfaceOps surfaceOps) {
            //将SurfaceProvider中的Surface与previewsurface建立连接
            previewSurface = surfaceOps.getSurface();
            //初始化相机
            openCamera();
        }

        @Override
        public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {
        }

        @Override
        public void surfaceDestroyed(SurfaceOps surfaceOps) {
        }
    };

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }


}